import { ipcMain } from 'electron';
/**主进程事件*/
export class MainEvent {


    /**
     * 一次性事件
     */
    static once(eventName: string, callback: (...args: any[]) => any) {
        ipcMain.once(eventName, async (event, ...args) => {
            //去除uuid
            let newArgs = args.slice(0, args.length - 1);
            let res = await callback(...newArgs);
            event.reply(eventName + ":" + JSON.stringify(args), res);
        })
    }

    /**
     * 事件监听
     */
    static on(eventName: string, callback: (...args: any[]) => any) {

        ipcMain.on(eventName, async (event, ...args) => {
             //去除uuid
             let newArgs = args.slice(0, args.length - 1);
             let res = await callback(...newArgs);
            event.reply(eventName + ":" + JSON.stringify(args), res);
        })
    }

    private static getUuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    }
    private static emitCallback(eventName: string, args: any[]) {
        return new Promise<any>((resolve, reject) => {
            try {
                ipcMain.once(eventName + ":" + JSON.stringify(args), (__event, ...args: any[]) => {
                    //@ts-ignore
                    resolve(...args)
                })
            } catch (error) {
                reject(error);
            }
        })
    };
    /**
     * 发送事件
     */
    static emit(eventName: string, ...args: any[]) {
        args.push(this.getUuid());
        ipcMain.emit(eventName, ...args);
        return this.emitCallback(eventName, args);
    }



};